package de.jmda.core.util.xl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.google.common.collect.ArrayTable;

public abstract class Util
{
	public static Workbook workbook(String file) throws IOException
	{
		if (file == null)
		{
			throw new IllegalArgumentException("file must not be null");
		}

		return workbook(new File(file));
	}

	public static Workbook workbook(File file) throws IOException
	{
		if (file == null)
		{
			throw new IllegalArgumentException("file must not be null");
		}

		if (false == file.exists())
		{
			throw new FileNotFoundException("file '" + file.getPath() + "' not found");
		}

		if (file.isDirectory())
		{
			throw new IllegalArgumentException(
					file.getPath() + " is a directory, not a file");
		}

		boolean xssf;

		if (file.getName().endsWith(".xlsx"))
		{
			xssf = true;
		}
		else if (file.getName().endsWith(".xls"))
		{
			xssf = false;
		}
		else
		{
			throw new IllegalArgumentException(
					"unsupported file extension: " + file.getName());
		}

		try (FileInputStream fis = new FileInputStream(file))
		{
			if (xssf)
			{
				return new XSSFWorkbook(new FileInputStream(file));
			}
			else
			{
				return new HSSFWorkbook(new FileInputStream(file));
			}
		}
	}

	public static int rowCount(Sheet sheet)
	{
		return sheet.getLastRowNum() + 1;
	}

	public static int colCount(Sheet sheet)
	{
		int result = 0;

		for (int rowIdx = 0; rowIdx < rowCount(sheet); rowIdx++)
		{
			Row row = sheet.getRow(rowIdx);

			if (row == null)
			{
				continue;
			}

			if (row.getLastCellNum() > result)
			{
				result = row.getLastCellNum();
			}
		}

		return result;
	}

	public static StringBuffer asStringBuffer(
	    ArrayTable<Integer, Integer, String> table)
	{
		StringBuffer result = new StringBuffer();
		
		for (Integer rowKey : table.rowKeyList())
		{
			for (Integer colKey : table.columnKeyList())
			{
				result.append("[" + table.get(rowKey, colKey) + "]");
			}
			result.append(System.lineSeparator());
		}
		
		return result;
	}
}